package com.hskn.hss.module.tlcartype.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.tlcarmodel.entity.TlCarModel;
import com.hskn.hss.module.tlcarmodel.mapper.TlCarModelMapper;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.mapper.TlCarTypeMapper;
import com.hskn.hss.module.tlcartype.service.ITlCarTypeService;
import com.hskn.hss.module.userdepart.entity.SysUserDepart;
import com.hskn.hss.module.userdepart.mapper.SysUserDepartMapper;
import com.hskn.hss.utils.GroupingByUtils;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.redis.RedisUtil;
import com.hskn.hss.utils.redis.key.CarTypeKey;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-17
 */
@Service
public class TlCarTypeServiceImpl extends ServiceImpl<TlCarTypeMapper, TlCarType> implements ITlCarTypeService {

    @Resource
    TlCarTypeMapper tlCarTypeMapper;
    @Resource
    SysUserDepartMapper sysUserDepartMapper;
    @Resource
    TlCarModelMapper tlCarModelMapper;

    @Override
    public AjaxResult insert(TlCarType tlCarType) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserDepart::getUserid, uid);
        String deptid = sysUserDepartMapper.selectOne(queryWrapper).getDepid();

        tlCarType.setCreateby(uid);
        tlCarType.setCreatetime(new Date());
        tlCarType.setDeptid(deptid);
        if (tlCarType.getStatus() == null || tlCarType.getStatus().isEmpty()) {
            tlCarType.setStatus("1");
        }
        tlCarTypeMapper.insert(tlCarType);
        return AjaxResult.success("操作成功");
    }

    @Override
    public AjaxResult update(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        TlCarType tlCarType = params.getObject("data", TlCarType.class);
        tlCarType.setUpdateby(uid);
        tlCarType.setUpdatetime(new Date());
        tlCarTypeMapper.updateById(tlCarType);
        return AjaxResult.success("操作成功");
    }

    @Override
    public AjaxResult deletebatchbyid(TlCarType tlCarType) throws HssException {
        String ids = tlCarType.getIds();
        String[] idArray = ids.split(",");
        tlCarTypeMapper.deleteBatchIds(Arrays.asList(idArray));
        return AjaxResult.success("操作成功");
    }

    @Override
    public AjaxResult deletebyid(JSONObject params) throws HssException {
        String id = params.getString("id");
        tlCarTypeMapper.deleteById(id);
        return AjaxResult.success("操作成功");
    }

    @Override
    public TlCarType getDetail(JSONObject params) throws HssException {
        String id = params.getString("id");
        TlCarType tlCarType = tlCarTypeMapper.selectById(id);
        return tlCarType;
    }

    @Override
    public List getSelectList(JSONObject params) throws HssException {
        String status = params == null ? "" : params.getString("status");
        Map<String,String> map = new HashMap<>();
        map.put("status",status);
        List<Map> resultList = tlCarTypeMapper.getSelectList(map);
        for (Map typemap : resultList) {
            String typeid = String.valueOf(typemap.get("id"));
            List<TlCarModel> modelList = tlCarModelMapper.getSelectList(typeid,status);
            typemap.put("models", modelList);
        }
        return resultList;
    }

    @Override
    @DataScope(deptAlias = "deptid", userAlias = "createby, updateby")
    public JSONObject getList(BaseEntity entity, JSONObject params) throws HssException {
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        JSONObject json = new JSONObject();

        Map<String, Object> map = new HashMap();
        map.put("operationtypeid", params.getString("operationtypeid"));
        map.put("typename", params.getString("typename"));
        map.put("status", params.getString("status"));
        map.put("params", entity.getParams());

        Page<TlCarType> listPage = new Page<>(page, size, true);
        IPage<TlCarType> iPage = tlCarTypeMapper.listTlCarType(listPage, map);
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("resultlist", iPage.getRecords());
        return json;
    }

    @Override
    public TlCarType getFromRedis(String carTypeId) {
        TlCarType tlCarType = null;
        if (StringUtils.isEmpty(carTypeId)) {
            return null;
        }
        try {
            tlCarType = RedisUtil.get(CarTypeKey.token, carTypeId, TlCarType.class);
            if (null == tlCarType) {
                tlCarType = tlCarTypeMapper.selectById(carTypeId);
                RedisUtil.set(CarTypeKey.token, carTypeId, tlCarType);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return tlCarType;
    }

    @Override
    public Map<String, TlCarType> getCarTypeMap(QueryWrapper<TlCarType> carTypeQueryWrapper) {
        List<TlCarType> carTypeList = tlCarTypeMapper.selectList(carTypeQueryWrapper);
        Map<String, TlCarType> carTypeMap = new HashMap<>();
        if (!carTypeList.isEmpty()) {
            carTypeMap = GroupingByUtils.getGroupingForMapEntity(carTypeList, TlCarType::getId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }
        return carTypeMap;
    }
}
